<template>
  <div class="article-list-container">
    <!-- 页面头部 -->
    <div class="list-header">
      <div class="header-left">
        <h1 class="page-title">我的文章</h1>
        <p class="page-subtitle">管理您发布的所有文章</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>
          发布文章
        </el-button>
      </div>
    </div>

    <!-- 筛选工具栏 -->
    <div class="filter-toolbar">
      <div class="filter-left">
        <el-radio-group v-model="filterStatus" @change="handleStatusChange">
          <el-radio-button value="">全部</el-radio-button>
          <el-radio-button :value="1">已发布</el-radio-button>
          <el-radio-button :value="0">草稿</el-radio-button>
        </el-radio-group>
      </div>
      <div class="filter-right">
        <el-button :loading="loading" @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 文章列表 -->
    <div class="article-list">
      <el-card v-if="loading" class="loading-card">
        <div class="loading-content">
          <el-icon class="is-loading"><Loading /></el-icon>
          <span>加载中...</span>
        </div>
      </el-card>

      <div v-else-if="articles.length === 0" class="empty-state">
        <el-empty description="暂无文章">
          <el-button type="primary" @click="handleCreate"
            >发布第一篇文章</el-button
          >
        </el-empty>
      </div>

      <div v-else class="article-grid">
        <el-card
          v-for="article in articles"
          :key="article.id"
          class="article-card"
          shadow="hover"
        >
          <!-- 文章封面 -->
          <div class="article-cover">
            <img
              v-if="article.coverImage"
              :src="formatImageUrl(article.coverImage)"
              :alt="article.title"
              class="cover-image"
            />
            <div v-else class="cover-placeholder">
              <el-icon><Document /></el-icon>
            </div>

            <!-- 状态标签 -->
            <div class="status-badges">
              <el-tag
                :type="getStatusType(article.status)"
                size="small"
                class="status-tag"
              >
                {{ getStatusText(article.status) }}
              </el-tag>
              <el-tag
                v-if="isTruthy(article.isOriginal)"
                type="success"
                size="small"
                class="original-tag"
              >
                原创
              </el-tag>
              <el-tag
                v-if="isTruthy(article.isTop)"
                type="warning"
                size="small"
                class="top-tag"
              >
                置顶
              </el-tag>
            </div>
          </div>

          <!-- 文章信息 -->
          <div class="article-info">
            <h3 class="article-title" @click="handleView(article)">
              {{ article.title }}
            </h3>
            <p class="article-summary">{{ article.summary }}</p>

            <!-- 文章标签 -->
            <div
              v-if="article.tags && article.tags.length > 0"
              class="article-tags"
            >
              <el-tag
                v-for="tag in article.tags"
                :key="tag.id"
                :color="tag.color"
                size="small"
                class="article-tag"
              >
                {{ tag.name }}
              </el-tag>
            </div>

            <!-- 文章统计 -->
            <div class="article-stats">
              <div class="stat-item">
                <el-icon><View /></el-icon>
                <span>{{ formatNumber(article.viewCount) }}</span>
              </div>
              <div class="stat-item">
                <el-icon><Star /></el-icon>
                <span>{{ formatNumber(article.likeCount) }}</span>
              </div>
              <div class="stat-item">
                <el-icon><ChatDotRound /></el-icon>
                <span>{{ formatNumber(article.commentCount) }}</span>
              </div>
              <div class="stat-item">
                <el-icon><Collection /></el-icon>
                <span>{{ formatNumber(article.collectCount) }}</span>
              </div>
            </div>

            <!-- 时间信息 -->
            <div class="article-time">
              <span class="create-time">
                创建于 {{ formatTime(article.createTime) }}
              </span>
              <span v-if="article.publishTime" class="publish-time">
                发布于 {{ formatTime(article.publishTime) }}
              </span>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="article-actions">
            <el-button size="small" @click="handleEdit(article)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button
              v-if="article.status === 0"
              size="small"
              type="success"
              @click="handlePublishDraft(article)"
            >
              <el-icon><Upload /></el-icon>
              发布
            </el-button>
            <el-button size="small" type="info" @click="handleView(article)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(article)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="articles.length > 0" class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Plus,
  Refresh,
  Loading,
  Document,
  View,
  Star,
  ChatDotRound,
  Collection,
  Edit,
  Upload,
  Delete
} from "@element-plus/icons-vue";
import { formatImageUrl, isTruthy } from "@/utils/avatar";

import {
  getMyArticleListApi,
  deleteMyArticleApi,
  publishDraftApi,
  type ArticlePublishResponse,
  UserArticleUtils
} from "@/api/user-article";

// 路由
const router = useRouter();

// 响应式数据
const loading = ref(false);
const filterStatus = ref<number | "">("");
const articles = ref<ArticlePublishResponse[]>([]);

// 分页数据
const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
});

// 方法
const loadArticles = async () => {
  loading.value = true;
  try {
    console.log("📚 开始加载文章列表...", {
      current: pagination.current,
      size: pagination.size,
      status: filterStatus.value
    });

    const params = {
      current: pagination.current,
      size: pagination.size,
      status: filterStatus.value === "" ? undefined : filterStatus.value
    };

    const response = await getMyArticleListApi(params);
    console.log("📝 API响应:", response);

    if (response.code === 200) {
      // 灵活处理响应数据格式
      if (Array.isArray(response.data)) {
        articles.value = response.data;
        pagination.total = response.data.length;
      } else if (response.data && typeof response.data === "object") {
        // 分页数据格式
        articles.value = response.data.records || response.data.list || [];
        pagination.total = response.data.total || 0;
      } else {
        articles.value = [];
        pagination.total = 0;
      }

      console.log("✅ 文章列表加载成功", {
        count: articles.value.length,
        total: pagination.total
      });
    } else {
      console.warn("⚠️ API返回错误:", response);
      ElMessage.error(response.message || "获取文章列表失败");
    }
  } catch (error) {
    console.error("❌ 获取文章列表失败:", error);

    // 更详细的错误处理
    let errorMessage = "获取文章列表失败";
    if (error?.response?.status === 401) {
      errorMessage = "登录已过期，请重新登录";
    } else if (error?.response?.status === 403) {
      errorMessage = "没有权限访问";
    } else if (error?.response?.data?.message) {
      errorMessage = error.response.data.message;
    } else if (error?.message) {
      errorMessage = error.message;
    }

    ElMessage.error(errorMessage);
  } finally {
    loading.value = false;
  }
};

const handleCreate = () => {
  router.push("/user/article/publish");
};

const handleEdit = (article: ArticlePublishResponse) => {
  // 使用发布页面的编辑模式
  console.log("✏️ 编辑文章:", article.id);
  router.push(`/user/article/publish?id=${article.id}`);
};

const handleView = (article: ArticlePublishResponse) => {
  router.push(`/user/article/${article.id}`);
};

const handlePublishDraft = async (article: ArticlePublishResponse) => {
  try {
    await ElMessageBox.confirm(
      `确定要发布文章"${article.title}"吗？`,
      "确认发布",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info"
      }
    );

    console.log("🚀 开始发布草稿:", article.id);
    const response = await publishDraftApi(article.id);

    if (response.code === 200) {
      console.log("✅ 草稿发布成功");
      ElMessage.success("文章发布成功");
      await loadArticles();
    } else {
      console.warn("⚠️ 发布失败:", response);
      ElMessage.error(response.message || "发布失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("发布文章失败:", error);
      ElMessage.error("发布文章失败");
    }
  }
};

const handleDelete = async (article: ArticlePublishResponse) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除文章"${article.title}"吗？删除后不可恢复。`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    console.log("🗑️ 开始删除文章:", article.id);
    const response = await deleteMyArticleApi(article.id);

    if (response.code === 200) {
      console.log("✅ 文章删除成功");
      ElMessage.success("文章删除成功");
      await loadArticles();
    } else {
      console.warn("⚠️ 删除失败:", response);
      ElMessage.error(response.message || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除文章失败:", error);
      ElMessage.error("删除文章失败");
    }
  }
};

const handleStatusChange = () => {
  pagination.current = 1;
  loadArticles();
};

const handleRefresh = () => {
  loadArticles();
};

const handleSizeChange = (size: number) => {
  pagination.size = size;
  pagination.current = 1;
  loadArticles();
};

const handleCurrentChange = (current: number) => {
  pagination.current = current;
  loadArticles();
};

// 工具函数
const getStatusText = (status: number): string => {
  return UserArticleUtils.getArticleStatusText(status);
};

const getStatusType = (status: number): string => {
  switch (status) {
    case 0:
      return "info"; // 草稿
    case 1:
      return "success"; // 已发布
    case 2:
      return "danger"; // 已删除
    default:
      return "info";
  }
};

const formatNumber = (num: number): string => {
  return UserArticleUtils.formatNumber(num);
};

const formatTime = (time: string): string => {
  return UserArticleUtils.formatTime(time);
};

// 生命周期
onMounted(() => {
  loadArticles();
});
</script>

<style scoped lang="scss">
// 响应式设计
@media (width <= 1200px) {
  .article-list-container {
    .article-list {
      .article-grid {
        grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
        gap: 18px;
      }
    }
  }
}

@media (width <= 768px) {
  .article-list-container {
    .list-header {
      flex-direction: column;
      gap: 20px;
      align-items: flex-start;
      padding: 24px;
      margin-bottom: 0;

      .header-left {
        .page-title {
          font-size: 24px;
        }

        .page-subtitle {
          font-size: 14px;
        }
      }

      .header-actions {
        display: flex;
        justify-content: center;
        width: 100%;

        .el-button {
          width: 100%;
          max-width: 280px;
          padding: 14px 32px;
          font-size: 16px;
        }
      }
    }

    .filter-toolbar {
      flex-direction: column;
      gap: 16px;
      align-items: stretch;
      padding: 16px 24px;
      margin: 0;

      .filter-left {
        .el-radio-group {
          display: flex;
          width: 100%;

          .el-radio-button {
            flex: 1;

            .el-radio-button__inner {
              width: 100%;
              padding: 12px 8px;
              font-size: 14px;
              text-align: center;
            }
          }
        }
      }

      .filter-right {
        .el-button {
          width: 100%;
          padding: 12px 20px;
          font-size: 15px;
        }
      }
    }

    .article-list {
      padding: 16px;

      .loading-card {
        margin: 0;

        .loading-content {
          padding: 50px 20px;
          font-size: 15px;
        }
      }

      .empty-state {
        padding: 60px 16px;

        .el-empty {
          padding: 32px 20px;
        }
      }

      .article-grid {
        grid-template-columns: 1fr;
        gap: 16px;

        .article-card {
          margin: 0;

          .article-cover {
            height: 160px;
          }

          .article-info {
            padding: 16px;

            .article-title {
              margin-bottom: 12px;
              font-size: 16px;
              line-height: 1.3;
            }

            .article-summary {
              margin-bottom: 16px;
              -webkit-line-clamp: 2;
              font-size: 14px;
            }

            .article-tags {
              margin-bottom: 16px;

              .article-tag {
                padding: 3px 10px;
                font-size: 11px;
              }
            }

            .article-stats {
              gap: 16px;
              padding: 12px 0;

              .stat-item {
                font-size: 13px;

                .el-icon {
                  font-size: 15px;
                }
              }
            }

            .article-time {
              flex-direction: column;
              gap: 4px;
              align-items: flex-start;
              font-size: 12px;

              .create-time,
              .publish-time {
                padding: 2px 6px;
                font-size: 11px;
              }
            }
          }

          .article-actions {
            gap: 8px;
            padding: 0 20px 20px;

            .el-button {
              flex: 1;
              min-width: 0;
              padding: 10px 8px;
              font-size: 12px;

              .el-icon {
                margin-right: 4px;
              }
            }
          }
        }
      }
    }

    .pagination-container {
      padding: 24px 16px;
      margin: 16px;

      .el-pagination {
        justify-content: center;

        .el-pagination__total,
        .el-pagination__sizes {
          display: none;
        }
      }
    }
  }
}

@media (width <= 480px) {
  .article-list-container {
    .list-header {
      padding: 20px 16px;

      .header-left {
        .page-title {
          font-size: 22px;
        }
      }

      .header-actions {
        .el-button {
          padding: 12px 24px;
          font-size: 15px;
        }
      }
    }

    .filter-toolbar {
      padding: 16px;
      margin: 0 8px 16px;
      border-radius: 12px;

      .filter-left {
        .el-radio-group {
          .el-radio-button {
            .el-radio-button__inner {
              padding: 10px 6px;
              font-size: 13px;
            }
          }
        }
      }
    }

    .article-list {
      padding: 0 8px 16px;

      .article-grid {
        gap: 12px;

        .article-card {
          .article-cover {
            height: 160px;
          }

          .article-info {
            padding: 16px;

            .article-title {
              font-size: 17px;
            }

            .article-summary {
              font-size: 13px;
            }

            .article-stats {
              gap: 12px;

              .stat-item {
                font-size: 12px;

                .el-icon {
                  font-size: 14px;
                }
              }
            }
          }

          .article-actions {
            padding: 0 16px 16px;

            .el-button {
              padding: 8px 6px;
              font-size: 11px;
              border-radius: 12px;
            }
          }
        }
      }
    }

    .pagination-container {
      padding: 20px 8px;
      margin: 8px;
    }
  }
}

// 暗色主题适配
@media (prefers-color-scheme: dark) {
  .article-list-container {
    background: #1a1a1a;

    .list-header {
      background: #2d2d2d;
      border-bottom-color: #404040;

      .header-left {
        .page-title {
          color: #e5e5e5;
        }

        .page-subtitle {
          color: #b0b0b0;
        }
      }
    }

    .filter-toolbar {
      background: #2d2d2d;
      border-bottom-color: #404040;
    }

    .article-list {
      .loading-card {
        background: #2d2d2d;
        border-color: #404040;

        .loading-content {
          color: #b0b0b0;
        }
      }

      .empty-state {
        .el-empty {
          background: #2d2d2d;
          border-color: #404040;
        }
      }

      .article-grid {
        .article-card {
          background: #2d2d2d;
          border-color: #404040;

          .article-cover {
            .cover-placeholder {
              color: #666;
              background: #1a1a1a;
            }

            .status-badges {
              .status-tag,
              .original-tag,
              .top-tag {
                color: #e5e5e5;
                background-color: #2d2d2d;
                border: 1px solid #404040;
              }
            }
          }

          .article-info {
            .article-title {
              color: #e5e5e5;

              &:hover {
                color: #409eff;
              }
            }

            .article-summary {
              color: #b0b0b0;
            }

            .article-tags {
              .article-tag {
                color: #b0b0b0;
                background: #1a1a1a;
                border: 1px solid #404040;
              }
            }

            .article-stats {
              border-top: 1px solid #404040;
              border-bottom: 1px solid #404040;

              .stat-item {
                color: #a0a0a0;

                .el-icon {
                  color: #409eff;
                }

                &:hover {
                  color: #409eff;
                }
              }
            }

            .article-time {
              color: #909090;

              .create-time {
                color: #a0a0a0;
                background: #1a1a1a;
                border: 1px solid #404040;
              }

              .publish-time {
                color: #64b5f6;
                background: #1e3a5f;
                border: 1px solid #2e5a8f;
              }
            }
          }
        }
      }
    }

    .pagination-container {
      background: #2d2d2d;
      border-top-color: #404040;
    }
  }
}

.article-list-container {
  min-height: 100vh;
  padding: 0;
  background: #f8f9fa;

  .list-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 32px 36px;
    margin-bottom: 0;
    background: #fff;
    border-bottom: 1px solid #e9ecef;

    .header-left {
      .page-title {
        margin: 0 0 6px;
        font-size: 28px;
        font-weight: 700;
        color: #495057;
      }

      .page-subtitle {
        margin: 0;
        font-size: 15px;
        font-weight: 500;
        color: #6c757d;
      }
    }

    .header-actions {
      .el-button {
        padding: 12px 24px;
        font-weight: 600;
        border-radius: 6px;
        transition: all 0.3s;

        &:hover {
          box-shadow: 0 4px 12px rgb(64 158 255 / 25%);
          transform: translateY(-2px);
        }
      }
    }
  }

  .filter-toolbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px 36px;
    margin: 0;
    background: #fff;
    border-bottom: 1px solid #e9ecef;

    .filter-left {
      .el-radio-group {
        .el-radio-button {
          &:first-child .el-radio-button__inner {
            border-radius: 6px 0 0 6px;
          }

          &:last-child .el-radio-button__inner {
            border-radius: 0 6px 6px 0;
          }

          .el-radio-button__inner {
            padding: 10px 20px;
            font-weight: 500;
            transition: all 0.3s;
          }
        }
      }
    }

    .filter-right {
      .el-button {
        padding: 10px 20px;
        font-weight: 500;
        border-radius: 6px;
        transition: all 0.3s;

        &:hover {
          box-shadow: 0 2px 8px rgb(0 0 0 / 15%);
          transform: translateY(-1px);
        }
      }
    }
  }

  .article-list {
    padding: 24px;

    .loading-card {
      background: #fff;
      border: 1px solid #e9ecef;
      border-radius: 8px;
      box-shadow: none;

      .loading-content {
        display: flex;
        gap: 12px;
        align-items: center;
        justify-content: center;
        padding: 60px;
        font-size: 16px;
        font-weight: 500;
        color: #6c757d;

        .el-icon {
          font-size: 24px;
        }
      }
    }

    .empty-state {
      display: flex;
      justify-content: center;
      padding: 80px 20px;

      .el-empty {
        padding: 40px;
        background: #fff;
        border: 1px solid #e9ecef;
        border-radius: 8px;
        box-shadow: none;
      }
    }

    .article-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
      gap: 20px;

      .article-card {
        overflow: hidden;
        background: #fff;
        border: 1px solid #e9ecef;
        border-radius: 8px;
        box-shadow: none;
        transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);

        &:hover {
          border-color: #ced4da;
          box-shadow: 0 4px 12px rgb(0 0 0 / 10%);
          transform: translateY(-6px) scale(1.01);
        }

        .article-cover {
          position: relative;
          height: 180px;
          overflow: hidden;
          border-radius: 0;

          .cover-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.4s ease;

            &:hover {
              transform: scale(1.1);
            }
          }

          .cover-placeholder {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100%;
            height: 100%;
            color: #adb5bd;
            background: #f8f9fa;

            .el-icon {
              font-size: 56px;
              opacity: 0.6;
            }
          }

          .status-badges {
            position: absolute;
            top: 16px;
            right: 16px;
            display: flex;
            flex-direction: column;
            gap: 8px;

            .status-tag,
            .original-tag,
            .top-tag {
              padding: 4px 10px;
              font-size: 11px;
              font-weight: 600;
              background-color: rgb(255 255 255 / 95%);
              border: 1px solid #e9ecef;
              border-radius: 4px;
              box-shadow: 0 2px 4px rgb(0 0 0 / 10%);
            }
          }
        }

        .article-info {
          padding: 20px;

          .article-title {
            display: -webkit-box;
            margin: 0 0 12px;
            overflow: hidden;
            -webkit-line-clamp: 2;
            font-size: 18px;
            font-weight: 700;
            line-height: 1.4;
            color: #495057;
            cursor: pointer;
            transition: all 0.3s ease;
            -webkit-box-orient: vertical;

            &:hover {
              color: #409eff;
            }
          }

          .article-summary {
            display: -webkit-box;
            margin: 0 0 16px;
            overflow: hidden;
            -webkit-line-clamp: 2;
            font-size: 14px;
            font-weight: 400;
            line-height: 1.6;
            color: #6c757d;
            -webkit-box-orient: vertical;
          }

          .article-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 6px;
            margin-bottom: 16px;

            .article-tag {
              padding: 3px 8px;
              font-size: 11px;
              font-weight: 500;
              color: #495057;
              background: #f8f9fa;
              border: 1px solid #dee2e6;
              border-radius: 3px;
              transition: all 0.3s;

              &:hover {
                background: #e9ecef;
                transform: translateY(-1px);
              }
            }
          }

          .article-stats {
            display: flex;
            gap: 16px;
            padding: 12px 0;
            margin-bottom: 14px;
            border-top: 1px solid #e9ecef;
            border-bottom: 1px solid #e9ecef;

            .stat-item {
              display: flex;
              gap: 4px;
              align-items: center;
              font-size: 13px;
              font-weight: 500;
              color: #6c757d;
              transition: all 0.3s;

              .el-icon {
                font-size: 14px;
                color: #409eff;
              }

              &:hover {
                color: #409eff;
                transform: translateY(-1px);
              }
            }
          }

          .article-time {
            display: flex;
            flex-wrap: wrap;
            gap: 6px;
            font-size: 12px;
            font-weight: 500;
            color: #6c757d;

            .create-time {
              padding: 2px 6px;
              margin-right: 0;
              color: #6c757d;
              background: #f8f9fa;
              border: 1px solid #dee2e6;
              border-radius: 3px;
            }

            .publish-time {
              padding: 2px 6px;
              color: #1976d2;
              background: #e3f2fd;
              border: 1px solid #bbdefb;
              border-radius: 3px;
            }
          }
        }

        .article-actions {
          display: flex;
          flex-wrap: wrap;
          gap: 8px;
          padding: 0 20px 20px;

          .el-button {
            padding: 6px 12px;
            font-size: 12px;
            font-weight: 600;
            border-radius: 4px;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

            &:hover {
              box-shadow: 0 2px 8px rgb(0 0 0 / 15%);
              transform: translateY(-2px);
            }
          }
        }
      }
    }
  }

  .pagination-container {
    display: flex;
    justify-content: center;
    padding: 32px;
    margin: 0;
    background: #fff;
    border-top: 1px solid #e9ecef;
    box-shadow: none;
  }
}

.pagination-container {
  background: rgb(45 45 45 / 90%);
}
</style>
